package cn.yz.filter;

import cn.yz.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

/**
 * JWT认证过滤器
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        System.out.println("==== JwtAuthenticationFilter ====");
        try {
            // 获取请求头中的token
            String token = getTokenFromRequest(request);

            if (StringUtils.hasText(token)) {
                log.debug("Processing JWT token for request: {}", request.getRequestURI());

                // 解析token
                Claims claims = jwtUtil.parseToken(token);
                String username = claims.getSubject();
                String userId = claims.get("userId", String.class);

                if (StringUtils.hasText(username)) {
                    log.debug("Authenticated user: {}", username);

                    // 创建认证对象
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username,
                        null,
                        Collections.singletonList(new SimpleGrantedAuthority("USER"))
                    );

                    // 设置认证信息到Security上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } else {
                log.debug("No JWT token found in request: {}", request.getRequestURI());
            }
        } catch (Exception e) {
            log.warn("JWT token validation failed for request: {}, error: {}", request.getRequestURI(), e.getMessage());
            // 不抛出异常，继续过滤器链，让Spring Security处理未认证的请求
        }

        filterChain.doFilter(request, response);
    }

    /**
     * 从请求头中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}